package zheezes.socket.impl.gd;

import java.util.Calendar;

import org.apache.log4j.Logger;

import zheezes.socket.Transput;


public class FrameSequence {
	private static Logger logger = Logger.getLogger(FrameSequence.class);
	
    private final int no; // set only when constructure
    private volatile boolean using = false;
    private Calendar lapse = null; // 
    private Transput transput = null;
    
    static {
    	logger.debug("loading");
    }

    public FrameSequence(int no) {
        this.no = no;
    }
    
	public synchronized boolean acquire() {
		if (using) {
			if (lapse != null && lapse.before(Calendar.getInstance())) { // if timeout
				if (transput != null) {
					transput.notifyAll();
					// mailbox.put(null);
				}
				transput = null;
				lapse = null;
				return true;
			} else { // using and not timeout(include not started)
				return false;
			}
		} else { // not used
			using = true;
			return true;
		}
	}

	public synchronized void release() {
		transput = null;
		lapse = null;
		using = false;
		// return mailbox;
	}

	public int getNo() {
		return no;
	}

	public Transput getTransput() {
		return transput;
	}

	public void setTransput(Transput transput) {
		this.transput = transput;
	}

	public void setTimeout(int msec) {
		lapse = Calendar.getInstance();
		lapse.add(Calendar.MILLISECOND, msec);
	}
}
